package com.example.httpclient.Crawler;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.example.httpclient.FileUtils.FileUtils;
import com.example.httpclient.uilts.CloseUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class download implements Runnable {
    private String urlString;
    private Handler mHandler;
    private final static String FileDir= Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator;
    private final static String PicDir="Crawler"+File.separator+"picture"+File.separator;
    private static int i=0;
    public download(String urlString,Handler mHandler){
        this.urlString=urlString;
        this.mHandler=mHandler;
    }
    @Override
    public void run() {
        OutputStream os=null;
        InputStream is=null;
        if(urlString.endsWith(".jpg")||urlString.endsWith(".png")||urlString.endsWith(".jpeg")){
            try {
                URL urL=new URL(urlString);
                HttpURLConnection httpURLConnection= (HttpURLConnection) urL.openConnection();
                if(httpURLConnection.getResponseCode()==200){
                    Message message=new Message();
                    FileUtils.CreateFile(FileDir+PicDir);
                    os= new FileOutputStream(new File(FileDir+PicDir+"pic"+i+".jpg"));
                    i++;
                    is=httpURLConnection.getInputStream();
                    message.what=0x02;
                    message.obj="正在下载"+FileDir+PicDir+i+".jpg";
                    mHandler.sendMessage(message);
                    int temp=0;
                    while ((temp=is.read())!=-1){
                        os.write(temp);
                    }
                    Message message1=new Message();
                    message1.what=0x02;
                    message1.obj=FileDir+PicDir+"pic"+i+".jpg"+"下载完成";
                    mHandler.sendMessage(message1);
                }
            } catch (IOException e) {
                e.printStackTrace();
                CloseUtil.closeAll(os,is);
                Message message=new Message();
                message.what=0x02;
                message.obj="下载出错";
                mHandler.sendMessage(message);
                mHandler.sendEmptyMessage(0x222);
            }finally {
                mHandler.sendEmptyMessage(0x222);
            }
        }
    }
}
